﻿Imports System.Text

Public Class Form1
    Private WithEvents server As New HarrySocketServer
    Private WithEvents client As New HarrySocketClient
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        server.StartListen()
        client.StartConnect()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        server.SendDataToAllClient(TextBox2.Text)
    End Sub
    Private Sub OnServerGetData(id As Integer, data As Byte(), dataType As HarryDataType) Handles server.OnReceivedData
        If TextBox1.InvokeRequired Then
            Dim d As New Action(Of Integer, Byte(), HarryDataType)(AddressOf OnServerGetData)
            TextBox1.Invoke(d, id, data, dataType)
            Return
        End If
        Select Case dataType
            Case HarryDataType.STR
                Dim text As String = Encoding.UTF8.GetString(data)
                TextBox1.AppendText(text) ' 推荐使用 AppendText 而非 +=，避免频繁重绘
            Case HarryDataType.BINARY
                ' 可选：处理二进制数据（例如显示为十六进制）
                ' TextBox1.AppendText($"[Binary: {data.Length} bytes]" & vbCrLf)
            Case Else
                ' 可选：处理其他类型或记录未知类型
                TextBox1.AppendText($"[Unknown data type: {dataType}]" & vbCrLf)
        End Select

        ' 可选：自动滚动到末尾
        TextBox1.ScrollToCaret()
    End Sub
    Private Sub OnClientGetData(data As Byte(), dataType As HarryDataType) Handles client.OnReceivedData
        If TextBox3.InvokeRequired Then
            Dim d As New Action(Of Byte(), HarryDataType)(AddressOf OnClientGetData)
            TextBox3.Invoke(d, data, dataType)
            Return
        End If
        Select Case dataType
            Case HarryDataType.STR
                Dim text As String = Encoding.UTF8.GetString(data)
                TextBox3.AppendText(text) ' 推荐使用 AppendText 而非 +=，避免频繁重绘
            Case HarryDataType.BINARY
                ' 可选：处理二进制数据（例如显示为十六进制）
                ' TextBox1.AppendText($"[Binary: {data.Length} bytes]" & vbCrLf)
            Case Else
                ' 可选：处理其他类型或记录未知类型
                TextBox3.AppendText($"[Unknown data type: {dataType}]" & vbCrLf)
        End Select

        ' 可选：自动滚动到末尾
        TextBox3.ScrollToCaret()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        client.SendData(TextBox4.Text)
    End Sub
End Class
